package java4_6.Homework4;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class Server extends Thread {
    private final Socket s;

    public Server(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        System.out.println("开始运行");
        try {

            BufferedReader br1 = new BufferedReader(new InputStreamReader(s.getInputStream()));//开启字符输入流

            PrintWriter pw1 = new PrintWriter(s.getOutputStream(), true);//             开启输出流

            SimpleDateFormat df1 = new SimpleDateFormat();
            df1.setLenient(false);
            df1.applyPattern("yyyy-MM-dd hh:mm:ss");
            Random r1 = new Random();
           ee: while (true) {

                pw1.println("选择查询服务：1.气温，2.风力，3.PM2.5，4.湿度,5.退出");
                String str = br1.readLine();
//               System.out.println("客户端："+s.getInetAddress()+"问："+str);
//                接收选择
                switch (str){
                    case  "1": {
                    Date d1 = new Date();
                    pw1.println("当前气温:" + r1.nextInt(40) + "°C" +" "+ df1.format(d1));
                        break;
                    }
                    case  "2": {
                    Date d1 = new Date();
                    pw1.println("当前风力:" + r1.nextInt(11) + " 级" +" "+ df1.format(d1));
                        break;
                }  case  "3": {
                    Date d1 = new Date();
                    pw1.println("当前PM2.5:" + r1.nextInt(31) + " " + df1.format(d1));
                        break;
                }  case  "4" :{
                    Date d1 = new Date();
                    pw1.println("当前湿度:" + r1.nextInt(51) + " " + df1.format(d1));
                        break ;
                } case  "5" :{
                    pw1.println("程序已退出");
                    break ee;
                }
                    default:{
                        pw1.println("请重新输入");
                        break;
                    }

            }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            ServerSocket S1 = new ServerSocket(5253);
            while (true) {
                new Server(S1.accept()).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
